<?php
/**
 * 消息管理
 */
namespace app\api\controller;

//use app\common\model\OrderModel;
use app\common\model\MessageOrder;
use app\common\model\MessageConsult;
use think\Controller;
use think\Db;
use think\Request;

class Message extends Common
{
    public $messageOrder;
    public $messageConsult;

    public function _initialize()
    {
        $this->messageOrder = new MessageOrder();
        $this->messageConsult = new MessageConsult();
    }


    /**
     * ajax设置订单已读
     * @return json_array
     */
    public function readOrderMessage()
    {
        if (!session('merchant')) {
            return returnJson(0, '未登录');
        }
        $msg_id = input('msg_id');
        if (!intval($msg_id)) return returnJson(0, '参数错误');
        $res = $this->messageOrder->update(
            ['is_read' => 1],
            [
                'merchant_id' => session('merchant.merchant_id'),
                'type' => 1,
                'is_read' => 0,
                'id'=>$msg_id
            ]
        );
        if ($res) {
            return returnJson(1, '已读成功');
        }
        return returnJson(0, '已读失败');
    }

    /**
     * ajax设置用户已读
     * @return json_array
     */
    public function readUserMessage()
    {
        if (!session('merchant')) {
            return returnJson(0, '未登录');
            //return parent::apiReturnFA('未登录');
        }
        $msg_id = input('msg_id');
        if (!intval($msg_id)) return returnJson(0, '参数错误');
        $res = $this->messageConsult->update(
            ['is_read' => 1],
            [
                'to_id' => session('merchant.merchant_id'),
                'type' => 1,
                'is_read' => 0,
                'id'=>$msg_id
            ]
        );
        if ($res) {
            return returnJson(1, '已读成功');
        }
        return returnJson(0, '已读失败');
    }

    /**
     * ajax设置系统消息已读
     * @return json_array
     */
    public function readSysMessage()
    {
        if (!session('merchant')) {
            return returnJson(0, '未登录');
        }
        $msg_id = input('msg_id');
        if (!intval($msg_id)) return returnJson(0, '参数错误');

        $merchant_id = session('merchant.merchant_id');
        $count = Db::name('message_read_record')->where(
            [
                'message_id'=>$msg_id,
                'merchant_id' => $merchant_id
            ]
        )->count();
        if (intval($count) > 0) return returnJson(0, '该消息已读');

        $res = Db::name('message_read_record')->insert(
            [
                'message_id'=>$msg_id,
                'merchant_id' => $merchant_id,
                'create_time' => time()
            ]
        );
        if ($res) {
            return returnJson(1, '已读成功');
        }
        return returnJson(0, '已读失败');
    }

    /**
     * ajax获取消息提示框数据信息
     * @return json_array
     */
    public function getMessageTips()
    {
        if (!session('merchant')) {
            return returnJson(0, '未登录');
        }
        $data = [];
        //1.系统消息
        $merchant_id = session('merchant.merchant_id');
        // 获取已读消息数量
        $ct_read = Db('message_read_record')
            ->where('merchant_id', $merchant_id)
            ->group('message_id')->count();

        // 获取所有消息数量
        $reg_time = Db('merchant')
            ->where('merchant_id', $merchant_id)
            ->value('merchant_reg_time');

        $ct_msg = Db('message')
            ->where(['message_push_type' => 4, 'message_is_delete' => 0])
            ->where('message_create_time', '>=', intval($reg_time))
            ->count();
        // 获取未读消息数量
        $data['ct_system'] = $ct_msg - $ct_read;
        $data['ct_system'] = $data['ct_system'] > 0 ? $data['ct_system'] : 0;

        //2.订单消息
        $data['ct_order'] = MessageOrder::where(
            [
                'merchant_id' => $merchant_id,
                'type' => 1,
                'is_read' => 0
            ]
        )->count();

        //3.用户留言
        $data['ct_user'] = MessageConsult::where(
            [
                'to_id' => $merchant_id,
                'type' => 1,
                'is_read' => 0
            ]
        )->count();

        $data['total'] = $data['ct_system'] + $data['ct_order'] + $data['ct_user'];
        // 如果有未读信息则返回消息数量
        if ($data['total']) return returnJson(1, 'ok', $data);
        return returnJson(0, 'no data');
    }

    /**
     * 商家客服详情(商家&用户聊天记录)
     */
    public function consultDetail()
    {
        // 接收参数
        $merchant_id = (int)session('merchant.merchant_id');
        $user_id = intval(input('user_id', 0));
        if (!$user_id) return returnJson(0, '参数错误');

        // 分页
        $pageSize = intval(input('page_number', 100));
        $page = intval(input('page', 1));

        // 获取当前商家与当前用户所有的聊天记录
        $sql = "SELECT store_id,`type`,content,create_time FROM `message_consult` 
                WHERE ((from_id={$user_id} AND to_id={$merchant_id} AND `type`=1) 
                OR (from_id={$merchant_id} AND to_id={$user_id} AND `type`=2)) ORDER BY id ASC";
        if ($page <= 1) {
            $limit = $pageSize;
        } else {
            $limit = ($page - 1) * $pageSize . ',' . $pageSize;
        }
        $data = Db::query($sql . ' limit ' . $limit);
        $user = Db::name('user')->field('nickname, face')->where('user_id', $user_id)->find();
//        $store = Db::name('store')
//            ->join('merchant', 'store.store_merchant_id = merchant.merchant_id')
//            ->where('store.store_merchant_id', $merchant_id)
//            ->field('store.store_name, store.store_face_img, merchant.merchant_nickname')
//            ->find();
        $store = Db::name('store')->where('store_merchant_id', $merchant_id)
                    ->field('store_id, store_name, store_face_img')->find();

        $result = [];
        $result['user_name'] = $user['nickname'] ?: '';
        $result['face_user'] = config('face_path') . ($user['face'] ?: 'defaultface.png')."@!custom";
        $result['face_merchant'] = config('oss_img_path') . 'store/face/' . ($store['store_face_img'] ?: 'defaultface.png')."@!store_perpor";
        $result['list'] = $data;

        //该用户 发给 该商家的 全部留言记录 标记为 已读
        Db::name('message_consult')->where('from_id', $user_id)->where('to_id', $merchant_id)->update(['is_read' => 1]);
        return returnJson(1, '获取数据成功', $result);
    }

    // 回复留言
    public function reply()
    {
        $msg_id = input('post.msg_id');
        $content = input('post.content');
        $storeId = input('post.store_id');
        $merchant = session('merchant.merchant_id');

        //$storeId = Db::name('store')->where('store_merchant_id', $merchant)->value('store_id');
        $toId = Db::name('message_consult')->where('id', $msg_id)->value('from_id');
        $res = Db::name('message_consult')->insert(
            [
                'store_id' => $storeId, 'from_id' => $merchant, 'to_id' => $toId, 'content' => $content,
                'type' => 2, 'target_id' => $msg_id, 'create_time' => time()
            ]
        );
        if ($res) {
            return returnJson(1, '回复成功', '');
        }
        return returnJson(0, '回复失败', '');
    }



    // ======================================
    // ============  私有方法   =============
    // ======================================



}
